package org.chen.aao.ai.controller;

import lombok.RequiredArgsConstructor;
import org.chen.aao.ai.service.AIService;
import org.chen.aao.ai.service.IChatService;
import org.chen.aao.common.ai.dto.ChatHistoryResponse;
import org.chen.aao.common.ai.dto.ChatRequest;
import org.chen.aao.common.ai.dto.ChatResponse;
import org.chen.aao.common.annotation.RateLimit;
import org.chen.aao.common.exception.BusinessException;
import org.chen.aao.common.response.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor
public class ChatController {

    private final IChatService aiService;

    @PostMapping("/chat")
    @RateLimit(key = "chat", time = 3600)
    public Result<ChatResponse> chat(@Validated @RequestBody ChatRequest request,
                                     HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(aiService.chat(request, userId));
    }

    @GetMapping("/chat/history")
    public Result<ChatHistoryResponse> getChatHistory(@RequestParam(value = "conversationId", required = false) String conversationId,
                                                      @RequestParam(value = "page", defaultValue = "1") int page,
                                                      @RequestParam(value = "size", defaultValue = "20") int size,
                                                      HttpServletRequest httpRequest) {
        System.out.println("Fetching chat history for conversationId: " + conversationId + ", page: " + page + ", size: " + size);
        Long userId = getUserId(httpRequest);
        return Result.success(aiService.getChatHistory(userId, conversationId, page, size));
    }

    private Long getUserId(HttpServletRequest request) {
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader == null || userIdHeader.trim().isEmpty()) {
            throw new BusinessException("用户未登录");
        }
        try {
            return Long.valueOf(userIdHeader);
        } catch (NumberFormatException e) {
            throw new BusinessException("用户ID格式错误");
        }
    }
}
